package com.wholesmart.web.component;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wholesmart.mapper.entity.Department;
import com.wholesmart.mapper.entity.User;
import com.wholesmart.service.DepartmentService;
import com.wholesmart.service.UserService;

/**
 * 获取当前用户信息的处理器
 * 
 * @author dyw
 * @date 2020年3月20日
 */

@Component
public class CurrentUserInfoHandler {

	@Autowired
	private UserService userService;
	@Autowired
	private DepartmentService departmentService;

	/**
	 * 通过用户名获取用户相关信息
	 * 
	 * @param username 用户名
	 * @return
	 */
	public CurrentUserInfo getCurrentUserInfo(String username) {
		CurrentUserInfo info = new CurrentUserInfo();
		User user = userService.getByUsername(username);
		if (user != null) {
			info.setUser(user);// 设置用户信息
			Long departmentId = user.getDepartmentId();
			Department department = departmentService.getById(departmentId);
			if (department != null) {
				Long depertmentId = department.getId();
				info.setDepartment(department);// 设置部门信息
				List<Department> departments = departmentService.recurDepartmentsById(depertmentId);
				info.setSubDepartments(departments);// 设置下级部门
				List<User> same = userService.getByDepertmentId(depertmentId);// 设置同部门用户信息
				info.setSameDepartmentUsers(same);
				List<User> sub = userService.getByDepertmentIds(getDepartmentIds(departments));// 设置下级部门用户信息
				info.setSubDepartmentUsers(sub);
			}
		}
		return info;
	}

	/**
	 * 抽取部门ID
	 * 
	 * @param departments 部门
	 * @return
	 */
	private List<Long> getDepartmentIds(List<Department> departments) {
		List<Long> result = new ArrayList<Long>();
		if (departments != null) {
			for (Department department : departments) {
				result.add(department.getId());
			}
		}
		return result;
	}
}
